using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace WXB
{
    public class Pool<T> where T : Component
    {
        static List<T> AllList = new List<T>();
        static int Num = 0;
        public static T Get(GameObject parent)
        {
            T t = null;
            //if (Application.isPlaying)
            {
                for (int i = AllList.Count - 1; i >= 0; --i)
                {
                    t = AllList[i];
                    AllList.RemoveAt(i);
                    if (t == null)
                        continue;

                    AddChild(parent, t.gameObject);
                    return t;
                }   
            }

            GameObject obj = NGUITools.AddChild(parent);
            //obj.hideFlags = HideFlags.DontSave;
            obj.name = typeof(T).Name + (++Num);
            t = obj.AddComponent<T>();
            Debug.Log("create:" + obj.name);
            return t;
        }

        public static void Free(T t)
        {
            //if (Application.isPlaying)
            {
                t.gameObject.SetActive(false);
                t.transform.parent = null;
                AllList.Add(t);
                Debug.Log("Free:" + t.gameObject.name);
            }
//             else
//             {
//                 Debug.Log("Free:" + t.gameObject.name);
//                 NGUITools.DestroyImmediate(t.gameObject);
//             }
        }

        static void AddChild(GameObject parent, GameObject go)
        {
            if (go != null && parent != null)
            {
                Transform t = go.transform;
                t.parent = parent.transform;
                t.localPosition = Vector3.zero;
                t.localRotation = Quaternion.identity;
                t.localScale = Vector3.one;
                go.layer = parent.layer;

                go.SetActive(true);
            }
        }
    }
}